# -*- coding: utf-8 -*-
import cv2, os, shutil, datetime, re, time
from threading import Thread
from hashlib import md5

PIC_HASH = {}


# https://blog.csdn.net/xiangliangyu/article/details/82585674
def md5_file(name):
    try:
        m = md5()
        a_file = open(name, 'rb')
        m.update(a_file.read())
        a_file.close()
        return m.hexdigest()
    except:
        return None


def no_water(old_dir, new_dir, dirlist):
    global PIC_HASH
    for ppic_dir in dirlist:
        print(ppic_dir)
        print(os.path.isdir(old_dir + ppic_dir))
        if os.path.isdir(old_dir + ppic_dir):
            sortfiles = os.listdir(old_dir + ppic_dir)
            if '.DS_Store' in sortfiles:
                sortfiles.remove('.DS_Store')
            sortfiles.sort()
            for old_file in sortfiles:
                filetype = "." + old_file.split(".")[len(old_file.split(".")) - 1]
                pic_name_front = old_file.split(filetype)[0]
                old_file = old_dir + ppic_dir + "/" + old_file
                jpg_name = pic_name_front + ".jpg"
                jpg_name = new_dir + ppic_dir + "/" + jpg_name
                try:
                    old_file_hash = md5_file(old_file)
                    old_file_tmp_hash_value = PIC_HASH.get(old_file_hash)
                    file_object = open('pichash.txt', 'a')
                    file_object.write(old_file + ":" + old_file_hash + '\n')
                    file_object.close()
                    if old_file_tmp_hash_value is None:
                        if not os.path.exists(new_dir + ppic_dir):
                            os.makedirs(new_dir + ppic_dir)
                        print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + "," + old_file + ",ing\n")
                        img = cv2.imread(old_file)
                        x, y, z = img.shape
                        if x < 100:
                            print(datetime.datetime.now().strftime(
                                "%Y-%m-%d %H:%M:%S") + "," + jpg_name + "too small , continue")
                        elif x > 5000:
                            print(datetime.datetime.now().strftime(
                                "%Y-%m-%d %H:%M:%S") + "," + jpg_name + "too big , continue")
                        elif not os.path.exists(jpg_name):
                            for i in range(x):
                                for j in range(y):
                                    varP = img[i, j]
                                    if 250 < sum(varP) < 765:
                                        img[i, j] = [255, 255, 255]
                            cv2.imwrite(jpg_name, img)
                            print("jpg_name:" + jpg_name)
                            PIC_HASH[old_file_hash] = old_file
                            print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + "," + old_file + ",done\n")
                        else:
                            print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + "," + jpg_name + ",exists\n")
                    elif old_file_tmp_hash_value is not None:
                        if os.path.exists(jpg_name):
                            print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + "," + jpg_name + ",exists\n")
                        else:
                            shutil.copyfile(old_file_tmp_hash_value, old_file)
                            shutil.copyfile(old_file, jpg_name)
                            print(datetime.datetime.now().strftime(
                                "%Y-%m-%d %H:%M:%S") + "," + jpg_name + " same with the old, continue")
                except Exception as e:
                    print("Exception:", e)
                    continue


if __name__ == '__main__':
    old_dir = "./old_pic/"
    new_dir = "./new_pic/"
    list0 = []
    list1 = []
    list2 = []
    for ppic_dir in os.listdir(old_dir):
        print(ppic_dir)
        print(os.path.isdir(old_dir + ppic_dir))
        if os.path.isdir(old_dir + ppic_dir):
            if re.compile(r'^[0-1].*').match(str(ppic_dir)):
                list0.append(ppic_dir)
            elif re.compile(r'^[2-3].*').match(str(ppic_dir)):
                list1.append(ppic_dir)
            elif re.compile(r'^[4-5].*').match(str(ppic_dir)):
                list2.append(ppic_dir)
            else:
                continue
    Thread(target=no_water, args=(old_dir, new_dir, list0)).start()
    Thread(target=no_water, args=(old_dir, new_dir, list1,)).start()
    Thread(target=no_water, args=(old_dir, new_dir, list2,)).start()
